package com.jwm.power.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.zhxu.bs.MapSearcher;
import cn.zhxu.bs.SearchResult;
import cn.zhxu.bs.util.MapUtils;
import com.jwm.power.mapper.QueryMapper;
import com.jwm.power.model.common.EnumResult;
import com.jwm.power.model.entity.Formcustoms;
import com.jwm.power.model.entity.Menus;
import com.jwm.power.model.entity.Users;
import com.jwm.power.model.reponse.ResponseData;
import com.jwm.power.service.UsersService;
import com.jwm.power.util.Ut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

//  用户管理
@Controller
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private MapSearcher mapSearcher;              // 注入 BeanSearcher 的检索器
    @Autowired
    private UsersService usersService;
    @Autowired
    private QueryMapper queryMapper;

    //  用户登录
    @RequestMapping(value = "/userLogin", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData UserLogin(HttpServletRequest request) {
        return usersService.UserLogin(request);
    }

    //  获取用户
    @RequestMapping(value = "/getUsers", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData GetUsers(HttpServletRequest request) {
        return usersService.GetUsers(request);
    }

    //  退出登录
    @RequestMapping(value = "/outLogin", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData OutLogin(HttpServletRequest request) {
        Users users = (Users) StpUtil.getSession().get("users");
        StpUtil.logout(users.getUserid());
        return new ResponseData(EnumResult.SUCCESS, null);
    }

    //  获取用户的菜单权限
    @RequestMapping(value = "/queryUserMenus", method = RequestMethod.GET)
    public void QueryUserMenus(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> map = new HashMap<>();
            Users users = (Users) StpUtil.getSession().get("users");
            map.put("jobCode", users.getJobcode());
            map.put("userName", users.getUsername());
            map.put("userid", users.getUserid());
            List<Map<String, Object>> mapList = queryMapper.queryUserMenus(map);
            Ut.toJson(response, mapList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //  获取用户数据
    @RequestMapping(value = "/queryUsers", method = RequestMethod.GET)
    public void QueryUsers(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 一行代码，实现一个用户检索接口（MapUtils.flat 只是收集前端的请求参数）
            String page = request.getParameter("cPage");
            String size = request.getParameter("pSize");
            String searchName = request.getParameter("searchName");
            String deptCode = request.getParameter("deptCode");
            String jobCode = request.getParameter("jobCode");
            Map<String, Object> params = MapUtils.builder()
                    .page(Integer.parseInt(page) - 1, Integer.parseInt(size))                   // 偏移 0 条，查询 15 条（推荐写法）
                    .field("name", searchName).op("ct")
                    .field("deptcode", deptCode).op("sw")
                    .field("jobcode", jobCode)
                    .build();
            Map<String, Object> dataMap = new HashMap<>();
            SearchResult<Map<String, Object>> searchResult = mapSearcher.search(Users.class, params);
            dataMap.put("data", searchResult.getDataList());
            dataMap.put("totals", searchResult.getTotalCount());
            Ut.toJson(response, dataMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //  设置用户
    @RequestMapping(value = "saveUsers", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData SaveUsers(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        return usersService.SaveUsers(request);
    }

    //  设置用户信息
    @RequestMapping(value = "saveUsersInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData SaveUsersInfo(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        return usersService.SaveUsersInfo(request);
    }

    //  设置用户部门数据权限
    @RequestMapping(value = "saveUserDepts", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData SaveUserDepts(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        return usersService.SaveUserDepts(request);
    }

    //  设置用户菜单数据权限
    @RequestMapping(value = "saveUserMenus", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData SaveUserMenus(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        return usersService.SaveUserMenus(request);
    }

    //  设置用户头像
    @RequestMapping(value = "saveUserImg", method = RequestMethod.POST)
    @ResponseBody
    public String SaveUserImg(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        return usersService.SaveUserImg(request);
    }


    //  获取自定义表单数据
    @RequestMapping(value = "/queryFormCustoms", method = RequestMethod.GET)
    public void QueryFormCustoms(HttpServletRequest request, HttpServletResponse response) {
        try {
            String moduleName = request.getParameter("modulename");

            if (Optional.ofNullable(moduleName).isPresent()) {
                List<Map<String, Object>> searchResult = mapSearcher.searchAll(Formcustoms.class, MapUtils.flat(request.getParameterMap()));
                Ut.toJson(response, searchResult);
            } else {
                List<Map<String, Object>> searchResult = mapSearcher.searchAll(Formcustoms.class, MapUtils.flat(request.getParameterMap()));
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("data", searchResult);
                dataMap.put("totals", searchResult.size());
                Ut.toJson(response, dataMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //  自定义表单数据
    //  保存表单数据
    @RequestMapping(value = "saveFormCustoms", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData SaveFormCustoms(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        return usersService.SaveFormCustoms(request);
    }
}